/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
/**
 * 网点添加页面
 *  */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, message, Row, Col } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import StationRecord from '@/components/StationRecord';
import DispatchPianqu from '@/components/_pages/Post/Area/DispatchPianqu';
import { getLStorage } from '@/utils/utils';
import styles from './style.less';
import { changePostName } from '../../utils/changePostCompanyName';
import AddOutlets from './components/AddOutlets';

const companyName = {
  yz: '快宝',
  post: '中邮',
  yjy: '驿加易',
};

@connect(({ loading, allocation, station, info, setting, user }) => ({
  allocation,
  station,
  userInfo: user.currentUser.user_info,
  getListLoading: loading.effects['allocation/getPostList'],
  addLoading: loading.effects['allocation/addOption'],
  editLoading: loading.effects['allocation/correctOption'],
  getCode: loading.effects['allocation/getCode'],
  fakeAccount: info.companyData.user_info.realAccount == 2, // 假账号
  ...setting,
}))
@Form.create()
export default class Outlets extends PureComponent {
  constructor(props) {
    super(props);
    const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};
    const isCompany = area_ids == '*';
    const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
    const area_id = gp_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : gp_area_ids[0];
    this.state = {
      isSuccess: false,
      area_id,
    };
  }

  // modal的确定按钮
  modalSubmit = (closeModal, type) => {
    const {
      dispatch,
      allocation,
      form,
      fakeAccount,
      options: { key: userKey },
    } = this.props;
    const { oneOption } = allocation;
    const { branch_code, brand } = oneOption;
    const values = form.getFieldsValue();
    const { area_id } = this.state;

    const checkEmpty = {
      previous_station_code: '上一站编号',
      next_station_code: '下一站编号',
      brand: '快递品牌',
      branch_code: '网点编号',
      branch_name: '网点名称',
      previous_station_name: '上一站名称',
      user_name: '用户名',
      user_pwd: '密码',
      dev_id: '设备型号',
      dev_imei: '设备串号',
      arrival_gun_code: '到件巴枪设备编号',
      delivery_gun_code: '派件巴枪设备编号',
      mobile: '手机号',
      verify_code: '验证码',
    };

    // 比对数据和原始数据，改变了就调接口，没改变就不做变动
    // 并且检测表格数据是否为空，若为空，提示，并拦截
    let onOff = true;
    let empty = false;
    Object.keys(values).forEach(key => {
      // 判断圆通尊者登录用户编号和用户名非必填
      if (type != 'yt') {
        if (values[key] == '') {
          empty = true;
          message.warning(`${checkEmpty[key]}不能为空！`);
          return;
        }
      } else if (values[key] == '') {
        empty = true;
        message.warning(`${checkEmpty[key]}不能为空！`);
        return;
      }
      values[key] != oneOption[key] && (onOff = false);
    });

    if (empty) return;
    if (onOff && type != 'add') {
      dispatch({
        type: 'allocation/save',
        payload: {
          visible: false,
          type: '',
        },
      });
      closeModal({ visible: false });
      return;
    }

    switch (type) {
      case 'add':
        if (fakeAccount && ['yd', 'yt'].includes(values.brand)) {
          message.error(
            `您的网点暂时无法添加${changePostName(values.brand)}网点，如需添加请联系${
              companyName[userKey]
            }。`,
          );
          return;
        }
        dispatch({
          type: 'allocation/addOption',
          payload: {
            ...values,
            area_id,
          },
        }).then(() => {
          closeModal({ visible: false });
        });
        break;
      case 'correct':
        // eslint-disable-next-line no-case-declarations
        const { branch_name, mobile, verify_code } = values;
        dispatch({
          type: 'allocation/correctOption',
          payload: {
            brand: changePostName(oneOption.brand),
            branch_name,
            branch_code,
            amend_branch_code: branch_code == values.branch_code ? '' : values.branch_code,
            mobile,
            verify_code,
            area_id,
          },
        }).then(() => {
          closeModal({ visible: false });
        });
        break;

      default:
        if (type == 'zt' || type == 'sto') {
          // 中通和申通只做展示，不做修改
          dispatch({
            type: 'allocation/save',
            payload: {
              visible: false,
              type: '',
            },
          });
        } else if (type == 'yt' || type == 'yd' || type == 'jt' || type == 'fw' || type == 'ems') {
          dispatch({
            type: 'allocation/setScanOption',
            payload: {
              brand: changePostName(brand),
              branch_code,
              ...values,
            },
          });
        }
        closeModal({ visible: false });
        break;
    }
  };

  addNewOutlets = () => {
    // 添加新网点信息
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: { visible: true, type: 'add' },
    });
  };

  editOutlets = record => {
    // 修改网点信息
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        type: 'correct',
        oneOption: record,
        visible: true,
      },
    });
  };

  // 删除网点信息
  deleteOption(params, { brand, branch_code }) {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/deleteOption',
      payload: {
        brand: changePostName(brand),
        branch_code,
        is_del: 1,
        ...params,
      },
    });
  }

  onChangePianqu = area_id => {
    this.setState({
      area_id,
    });
  };

  render() {
    const {
      form,
      allocation: { postList, type },
      getListLoading,
      addLoading,
      editLoading,
    } = this.props;
    const { isSuccess, area_id } = this.state;
    const { resetFields } = form;
    const loading = type == 'add' ? addLoading : editLoading;

    return (
      <PageHeaderLayout
        title={
          <Row type="flex" justify="space-between">
            <Col>网点信息</Col>
            <Col>
              <DispatchPianqu type="gp" onChange={this.onChangePianqu} />
            </Col>
          </Row>
        }
      >
        <div className={styles.main}>
          <StationRecord
            type="outlets"
            dataSource={postList}
            submit={this.modalSubmit}
            resetFields={resetFields}
            isSuccess={isSuccess}
            addNewOutlets={this.addNewOutlets}
            editOutlets={this.editOutlets}
            handleDelet={this.deleteOption.bind(this, { area_id })}
            loading={getListLoading}
            confirmLoading={loading}
            area_id={area_id}
          >
            <AddOutlets form={form} />
          </StationRecord>
        </div>
      </PageHeaderLayout>
    );
  }
}
